//
//  MTLuckyViewController.swift
//  MT
//
//  Created by ooops on 2020/1/21.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result

class MTLuckyViewController: BaseViewController {
    
    private lazy var luckyProvider: MTProvider<MTLuckyAPI> = {
        let provider = MTProvider<MTLuckyAPI>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private lazy var lotteryLuckyProvider: MTProvider<MTLuckyAPI> = {
        let provider = MTProvider<MTLuckyAPI>()
        return provider
    }()
    
    private lazy var provider: MTProvider<MTClubApi> = MTProvider<MTClubApi>()
    
    let userProvider: MTProvider = MTProvider<UserCenterApi>()
    
    //let luckyProvider: MTProvider = MTProvider<MTLuckyAPI>()
    
    /// 背景图
    lazy var luckyBgImageV: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "choujiang-bg"))
        return imageV
    }()
    
    /// 文字图
    lazy var luckyWordImageV: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "word"))
        imageV.sizeToFit()
        return imageV
    }()
    
    /// 彩带
    lazy var luckyCaidaiImageV: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "caidai"))
        return imageV
    }()
    
    lazy var poolLabel: UILabel = {
        let l = UILabel()
        //l.font = PingFangSCMediumFont(17)
        //l.font = UIFont(name: "Arial Rounded MT Bold", size: 20)
        l.font = PingFangSCSemiboldFont(28)
        l.textColor = UIColor.im.xfd387c
        l.textAlignment = .center
        //l.text = "77777777"
        return l
    }()
    
    /// 彩带下面的图
    lazy var luckyTopImageV: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "choujiangpan-top"))
        return imageV
    }()
    
    /// 抽奖 - 奖品区域
    lazy var luckyContentImageV: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "choujiang-jiugongge"))
        imageV.isUserInteractionEnabled = true
        return imageV
    }()
    
    /// 奖品下面的区域
    lazy var luckyBottomImageV: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "choujiangpan-bottom"))
        imageV.isUserInteractionEnabled = true
        return imageV
    }()
    
    
    lazy var poolView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        return v
    }()
    
    lazy var ruleButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("规则", for: .normal)
        btn.addTarget(self, action: #selector(rule), for: .touchUpInside)
        btn.setTitleColor(UIColor.im.xfd387c, for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(14)
        return btn
    }()
    
    lazy var recordButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("记录", for: .normal)
        btn.addTarget(self, action: #selector(record), for: .touchUpInside)
        btn.setTitleColor(UIColor.im.xfd387c, for: .normal)
        btn.titleLabel?.font = PingFangSCRegularFont(14)
        return btn
    }()
    
    lazy var runButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "button-cj"), for: .normal)
        btn.setImage(UIImage(named: "button-cj-press"), for: .highlighted)
        btn.addTarget(self, action: #selector(runPool), for: .touchUpInside)
        return btn
    }()
    
//    lazy var luckyView: MTLuckyView = {
//        let lck = MTLuckyView(treasureArray: [])
//        lck.delegate = self
//        return lck
//    }()
    
    lazy var emptyView: MTLuckyEmptyView = {
        let emptyView: MTLuckyEmptyView = MTLuckyEmptyView(nil, nil) { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.loadPoolInfo()
        }
        return emptyView
    }()
    
    private var luckyView: MTLuckyView?
    /// 活动规则
    private var ruleString: String = ""
    /// 抽奖奖品数据
    private var result: [MTLuckyMoneyModel]?
    /// 中奖模型
    private var luckyModel: MTLuckyMoneyModel?
    
    private func setupUI() {
        view.addSubview(luckyBgImageV)
        view.addSubview(luckyWordImageV)
        view.addSubview(luckyCaidaiImageV)
        luckyCaidaiImageV.addSubview(poolLabel)
        view.addSubview(luckyTopImageV)
        view.addSubview(luckyContentImageV)
        luckyContentImageV.addSubview(poolView)
        //poolView.addSubview(luckyView)
        view.addSubview(luckyBottomImageV)
        luckyBottomImageV.addSubview(ruleButton)
        luckyBottomImageV.addSubview(recordButton)
        view.addSubview(runButton)
    }
    
    private func makeConstraint() {
        luckyBgImageV.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        luckyWordImageV.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(luckyCaidaiImageV.snp.top).offset(-10)
        }
        
        luckyCaidaiImageV.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.left.right.equalTo(luckyContentImageV)
            make.bottom.equalTo(luckyTopImageV.snp.top)
        }
        
        poolLabel.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.left.equalToSuperview().offset(45)
            make.right.equalToSuperview().offset(-45)
        }
        
        luckyTopImageV.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.left.right.equalTo(luckyBottomImageV)
            make.bottom.equalTo(luckyContentImageV.snp.top).offset(5)
        }
        
        luckyContentImageV.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalTo(luckyBottomImageV.snp.top)
            make.left.equalToSuperview().offset(24)
            make.right.equalToSuperview().offset(-24)
            make.height.equalTo((ScreenWidth - 48) * 382 / 332)
        }
        
        poolView.snp.makeConstraints { (make) in
            let width: CGFloat = ScreenWidth - ((16 * 382 / 332) * 2) - 48
            make.left.equalToSuperview().offset(16 * 382 / 332)
            make.right.equalToSuperview().offset(-16 * 382 / 332)
            make.top.equalToSuperview().offset(23 * 382 / 332)
            make.height.equalTo(width)
        }
        
//        luckyView.snp.makeConstraints { (make) in
//            make.edges.equalToSuperview()
//        }
        
        luckyBottomImageV.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(25)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
        }
        
        ruleButton.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(7)
            make.left.equalToSuperview().offset(40)
        }
        
        recordButton.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(7)
            make.right.equalToSuperview().offset(-40)
        }
        
        runButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview()
            make.width.equalTo(100)
            make.height.equalTo(87)
        }
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        makeConstraint()
        loadPoolInfo()
    }
    
    override func refreshView() {
        loadPoolInfo()
    }
}

extension MTLuckyViewController {
    
    /// 获取奖池及奖品信息
    private func loadPoolInfo() {
        poolView.removeAllSubviews()
        luckyProvider.rx.requestResult(.list).subscribe(onNext: { [weak self] (result:Result<MTLuckyModel, AnyError> , isCache:Bool) in
            guard let weakSelf = self else { return }
            switch result {
            case .success(let model):
                if model.code == 200, let r = model.result {
                    weakSelf.ruleString = model.rules ?? ""
                    if let ticketAmount = model.ticketAmount {
                        weakSelf.poolLabel.text = "\(ticketAmount)点券"
                    }
                    if r.count > 0 {
                        /// 有奖品数据
                        weakSelf.result = r
                        weakSelf.luckyView = MTLuckyView(treasureArray: r)
                        weakSelf.luckyView?.delegate = self
                        
                        weakSelf.poolView.addSubview(weakSelf.luckyView!)
                        weakSelf.luckyView!.snp.remakeConstraints { (make) in
                            make.edges.equalToSuperview()
                        }
                    } else {
                        /// 如果没有拿到奖品 / 网络出错了, 的处理 - 显示一个空界面
                        weakSelf.poolView.addSubview(weakSelf.emptyView)
                        
                        weakSelf.emptyView.snp.remakeConstraints { (make) in
                            make.edges.equalToSuperview()
                        }
                    }
                    
                } else {
                    /// 如果没有拿到奖品 / 网络出错了, 的处理 - 显示一个空界面
                    weakSelf.poolView.addSubview(weakSelf.emptyView)
                    
                    weakSelf.emptyView.snp.remakeConstraints { (make) in
                        make.edges.equalToSuperview()
                    }
                }
                break
            case .failure(_):
                /// 如果没有拿到奖品 / 网络出错了, 的处理 - 显示一个空界面
                weakSelf.poolView.addSubview(weakSelf.emptyView)
                
                weakSelf.emptyView.snp.remakeConstraints { (make) in
                    make.edges.equalToSuperview()
                }
                break
            }
            
        }).disposed(by: globalDisposedBag)
    }
    
    
    
    @objc private func rule() {
        let vc: MTLuckyRuleViewController = MTLuckyRuleViewController(rule: self.ruleString)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc private func record() {
        let vc: MTLuckyReportViewController = MTLuckyReportViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    /// 抽奖
    @objc private func runPool() {
        self.runButton.isUserInteractionEnabled = false
        /// 查询抽奖所需要消耗的钻石
        MTClubTool.config(provider: provider, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            let cost = model?.result?.cost ?? 100
            let userMoney = model?.result?.moeny ?? 0
            if model?.code == 200, userMoney < cost {
                UIAlertController.rx.show(in: weakSelf, title: "余额不足", message: "此次抽奖将花费\(cost)钻石", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                    /// 去充值的引导
                    if index == 1 {
//                        if let token = UserCenter.default.auth?.token {
//                            Navigate.safari(url: "\(RechargeH5BaseUrl)?token=\(token)").push()
//                        }
                        if UserDefaults.AppValidate.isValidate.storedBool == false {
                            let c = MTPaymentViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        } else {
                            let c = MTInAppPurchasesViewController()
                            weakSelf.navigationController?.pushViewController(c, animated: true)
                        }
                        
                    }
                    weakSelf.runButton.isUserInteractionEnabled = true
                })
                .disposed(by: globalDisposedBag)
            } else {
                /// 抽奖提示
                UIAlertController.rx.show(in: weakSelf, title: "提示", message: "此次抽奖将花费\(cost)钻石", buttons: [.cancel("取消"), .default("确定")]).subscribe(onSuccess: { [weak self] index in
                    guard let weakSelf = self else { return }
                    if index == 1 {
                        weakSelf.config()
                    }
                    weakSelf.runButton.isUserInteractionEnabled = true
                })
                .disposed(by: globalDisposedBag)
            }
        }) { (error) in

        }
    }
    
    /// 获取抽奖结果
    private func config() {
        if self.result == nil || (self.result?.count ?? 0) <= 0 {
            MBProgressHUD_JChat.show(text: "暂时无法抽奖", view: self.view, 2)
            return
        }
        
        self.runButton.isUserInteractionEnabled = false
        
        lotteryLuckyProvider.rx.requestResult(.lottery).subscribe(onNext: { [weak self] (result:Result<MTLuckyModel, AnyError> , isCache:Bool) in
            guard let weakSelf = self else { return }
            switch result {
            case .success(let model):
                if model.code == 600 {
                    UIAlertController.rx.show(in: weakSelf, title: "提示", message: "余额不足, 请前往充值", buttons: [.cancel("取消"), .default("去充值")]).subscribe(onSuccess: { index in
                        /// 去充值的引导
                        if index == 1 {
                            if UserDefaults.AppValidate.isValidate.storedBool == false {
                                let c = MTPaymentViewController()
                                weakSelf.navigationController?.pushViewController(c, animated: true)
                            } else {
                                let c = MTInAppPurchasesViewController()
                                weakSelf.navigationController?.pushViewController(c, animated: true)
                            }
                            
                        }
                        weakSelf.runButton.isUserInteractionEnabled = true
                    })
                    .disposed(by: globalDisposedBag)
                } else if model.code == 200 {
                    weakSelf.luckyModel = model.result_1
                    
                    for (i, v) in weakSelf.result!.enumerated() {
                        if v.id == weakSelf.luckyModel?.id {
                            weakSelf.luckyView!.testArray = [i]
                            break
                        }
                    }
                }
                
                break
            case .failure(_):
                weakSelf.luckyModel = nil
                break
            }
            
        }).disposed(by: globalDisposedBag)
    }
}

extension MTLuckyViewController: MTLuckyResultViewControllerDelegate {
    
    func runAgain() {
        runPool()
    }
    
}

extension MTLuckyViewController: MTLuckyViewDelagate {
    
    func luckViewStart() {
        
    }
    
    func luckViewStop() {
        self.runButton.isUserInteractionEnabled = true
        if let money = self.luckyModel?.ticketAmount {
            let vc: MTLuckyResultViewController = MTLuckyResultViewController("\(money)")
            vc.delegate = self
            let presentTransition: MTModalTransition = MTModalTransition()
            vc.transitioningDelegate = presentTransition
            vc.modalPresentationStyle = .custom
            vc.modalTransitionStyle = .crossDissolve
            DispatchQueue.main.async {
                self.navigationVC?.present(vc, animated: true, completion: nil)
            }
        }
        
        /// 刷新总奖池
        if let totalAmount = self.luckyModel?.totalAmount  {
            self.poolLabel.text = "\(totalAmount)"
        }
        
    }
    
}


extension MTLuckyViewController {
    
    override func yp_navigationBarTintColor() -> UIColor! {
        return UIColor(hex: 0xFFFFFF)
    }

    override func yp_navigtionBarConfiguration() -> YPNavigationBarConfigurations {
        return [.backgroundStyleColor, .styleBlack, .backgroundStyleTransparent]
    }
    
    override func yp_navigationBackgroundColor() -> UIColor! {
        return UIColor(hex: 0x000000)
    }
}
